<template>

  <div id="app">
    <router-view></router-view>
  </div>
</template>
<script>
import moment from 'moment'
import { mapState, mapMutations } from "vuex";
export default {
  data () {
    return {
      MsgWebSocrt: null,
    };
  },
  computed: {
    ...mapState(["token", "baseWebSocket"]),
  },
  watch: {
    token: function (val) {
      if (val && this.MsgWebSocrt == null) {
        this.MessageSocket(val)
      }
    },
  },
  created () {
    console.log("created")

    // let websocrt = new WebSocket()
  },
  mounted () {
    if (this.token && this.MsgWebSocrt == null) {
      this.MessageSocket(this.token)
    }
  },
  methods: {
    ...mapMutations(["pushMsg"]),
    MessageSocket (token) {
      console.log(encodeURIComponent(token))
      this.MsgWebSocrt = new WebSocket(this.baseWebSocket + 'api/WebSockets?token=' + encodeURIComponent(token))

      this.MsgWebSocrt.onopen = () => {
        console.log("onopen")
      }
      this.MsgWebSocrt.onclose = () => {
        console.log("onclose")
        this.MsgWebSocrt = null
      }
      this.MsgWebSocrt.onmessage = (res) => {
        let data = JSON.parse(res.data)
        data.title = moment(data.Addtime).format("YYYY-MM-DD HH:mm:ss"),
          data.message = data.Message1,
          this.pushMsg(data);

      }
      this.MsgWebSocrt.onerror = (res) => {
        console.log("onerror")
        console.log(res)
        this.MsgWebSocrt = null
      }
      // console.log(this.MsgWebSocrt)
      // this.MsgWebSocrt.close()
    },
  }
};
</script>

<style>
/*@import "./assets/css/theme-green/color-green.css";   浅绿色主题*/
</style>